//
//  NetWorkTool.swift
//  Mall-swift
//
//  Created by Bob on 2020/10/15.
//  Copyright © 2020 Bob. All rights reserved.
//

import UIKit
import Alamofire
import HandyJSON

open class NetWorkTool {
    
    private var session : Session?
    public static let share = NetWorkTool()
    private init() {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 20
        session = Session(configuration: configuration, delegate: SessionDelegate(), serverTrustManager: nil)
    }

    public func request(_ urlString: String,
                               method: HTTPMethod = .get,
                               parameters: Parameters? = nil,
                               encoding: ParameterEncoding? = nil,
                               headers: HTTPHeaders? = nil,
                               interceptor: RequestInterceptor? = nil,
                               sucess: ((_ code: Int?, _ data:Any?, _ msg:String?) -> Void)? = nil,
                               failure: ((_ code: Int?, _ data:Any?, _ msg:String?) -> Void)? = nil){
        
        guard let baseURLStr =  MAEnvMgr.share.env?.MADebugRequestBaseURL else {
            return
        }
        var encod: ParameterEncoding = (method == .get) ? URLEncoding.default : JSONEncoding.default
        if let inEncoding = encoding{
            encod = inEncoding
        }
        var url = baseURLStr + urlString
        if !urlString.starts(with: "/") {
            url = baseURLStr + "/" + urlString
        }
        
        
        session?.request(url, method: method, parameters: parameters, encoding: encod, headers: headers, interceptor: interceptor).responseJSON{response in
            
            let msgKey = "msg"
            let codeKey = "code"
            switch response.result {
            case .success(let value):
                if let result = value as? [String : Any] {
                    
                    let code = result[codeKey] as? Int
                    let msg = result[msgKey] as? String
                    let data = result["data"]
                    if let code = code, code == 0 {
                        // 成功
                        sucess?(code, data, msg)
                    } else {
                        failure?(code, data, msg)
                    }
                } else {
                    // 失败
                    failure?(nil, nil, "未识别接口返回的数据类型：")
                    print(type(of: value))
                }
            case .failure(let error):
                failure?(nil, nil, "接口出错了：" + error.localizedDescription)
            }
        }
        
        
    }
    
    
    
    
    
    public func request<T: HandyJSON>(_ urlString: String,
                               method: HTTPMethod = .get,
                               parameters: Parameters? = nil,
                               encoding: ParameterEncoding? = nil,
                               headers: HTTPHeaders? = nil,
                               interceptor: RequestInterceptor? = nil,
                               sucess: ((_ code: Int?, _ data:T?, _ msg:String?) -> Void)? = nil,
                               failure: ((_ code: Int?, _ data:Any?, _ msg:String?) -> Void)? = nil){
        
        guard let baseURLStr =  MAEnvMgr.share.env?.MADebugRequestBaseURL else {
            return
        }
        var encod: ParameterEncoding = (method == .get) ? URLEncoding.default : JSONEncoding.default
        if let inEncoding = encoding{
            encod = inEncoding
        }
        var url = baseURLStr + urlString
        if !urlString.starts(with: "/") {
            url = baseURLStr + "/" + urlString
        }
        
        
        session?.request(url, method: method, parameters: parameters, encoding: encod, headers: headers, interceptor: interceptor).responseJSON{response in
            
            let msgKey = "msg"
            let codeKey = "code"
            switch response.result {
            case .success(let value):
                if let result = value as? [String : Any] {
                    
                    let code = result[codeKey] as? Int
                    let msg = result[msgKey] as? String
                    let data = result["data"]
                    if let code = code, code == 0 {
                        // 成功
                        if let data = data as? [String: Any] {
                            sucess?(code, T.deserialize(from: data), msg)
                        }
                        else  {
                            failure?(code, data, msg)
                        }
                    } else {
                        failure?(code, data, msg)
                    }
                } else {
                    // 失败
                    failure?(nil, nil, "未识别接口返回的数据类型：")
                    print(type(of: value))
                }
            case .failure(let error):
                failure?(nil, nil, "接口出错了：" + error.localizedDescription)
            }
        }
        
        
        
        
        
    }
    
    
    public func requestList<T: HandyJSON>(_ urlString: String,
                               method: HTTPMethod = .get,
                               parameters: Parameters? = nil,
                               encoding: ParameterEncoding? = nil,
                               headers: HTTPHeaders? = nil,
                               interceptor: RequestInterceptor? = nil,
                               sucess: ((_ code: Int?, _ data:[T]?, _ msg:String?) -> Void)? = nil,
                               failure: ((_ code: Int?, _ data:Any?, _ msg:String?) -> Void)? = nil){
        
        guard let baseURLStr =  MAEnvMgr.share.env?.MADebugRequestBaseURL else {
            return
        }
        var encod: ParameterEncoding = (method == .get) ? URLEncoding.default : JSONEncoding.default
        if let inEncoding = encoding{
            encod = inEncoding
        }
        var url = baseURLStr + urlString
        if !urlString.starts(with: "/") {
            url = baseURLStr + "/" + urlString
        }
        
        
        session?.request(url, method: method, parameters: parameters, encoding: encod, headers: headers, interceptor: interceptor).responseJSON{response in
            
            let msgKey = "msg"
            let codeKey = "code"
            switch response.result {
            case .success(let value):
                if let result = value as? [String : Any] {
                    
                    let code = result[codeKey] as? Int
                    let msg = result[msgKey] as? String
                    let data = result["data"]
                    if let code = code, code == 0 {
                        // 成功
                        if let data = data as? [[String: Any]] {
                            let dsf = [T].deserialize(from: data)?.compactMap{$0}
                            sucess?(code, dsf, msg)
                        }
                        else  {
                            failure?(code, data, msg)
                        }
                    } else {
                        failure?(code, data, msg)
                    }
                } else {
                    // 失败
                    failure?(nil, nil, "未识别接口返回的数据类型：")
                    print(type(of: value))
                }
            case .failure(let error):
                failure?(nil, nil, "接口出错了：" + error.localizedDescription)
            }
        }
        
        
        
        
        
    }
    
}

